package com.mobileClientKernel.android.serviceLayer.httpTransportService.network;

import android.content.Intent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.mobileClientKernel.android.serviceManager.help.ReflectUtil;
import com.mobileClientKernel.android.serviceManager.network.JJBaseRequestMethod;
import com.mobileClientKernel.android.serviceManager.network.JJRequest;
import com.mobileClientKernel.android.serviceLayer.httpTransportService.info.JJTHttpTransportServiceInfoManager;
import com.mobileClientKernel.android.serviceLayer.httpTransportService.model.IJJTBaseModel;
import com.mobileClientKernel.android.serviceLayer.httpTransportService.urlconfig.JJTUrlConfigManager;
import com.mobileClientKernel.android.commonLayer.JJLog;
import org.json.JSONException;
import java.util.List;
import java.util.Map;

/**
 * Created by gongjian on 2018/4/26.
 */

public class JJTBaseRequest extends JJRequest {
    private org.json.JSONObject parameters;

    private boolean isEncryption;

    private JSONObject responseContentObject;
    public static final String FORCELOGOUT = "JJTHttpTransportServiceNotificationNameServerForceLogout";
    public static final String FORCELOGOUT_CODE = "code";
    public static final String FORCELOGOUT_CONTENT = "responseContentObject";

    public JJTBaseRequest(String identity, org.json.JSONObject parameters, boolean isEncryption, Class modelClass, boolean isSaveToMemory, boolean isSaveToDisk) {
        setIdentity(identity);
        setRequestMethod(JJBaseRequestMethod.Post);
        setIsSaveToMemory(isSaveToMemory);
        setIsSaveToDisk(isSaveToDisk);
        setModelClass(modelClass);

        this.parameters = parameters;
        setParametersForSavedFileName(this.parameters);

        this.isEncryption = isEncryption;

        if (JJTHttpTransportServiceInfoManager.getInstance().isUserDidOnLine()
                && JJTHttpTransportServiceInfoManager.getInstance().getUserID() != null) {
            setSensitiveDataForSavedFileName(JJTHttpTransportServiceInfoManager.getInstance().getUserID());
        }
    }

    @Override
    public String hostUrl() {
        String hostUrl = JJTUrlConfigManager.getInstance().serverHostWithIdentity(getIdentity());
        return hostUrl;
    }

    @Override
    public String pathUrl() {
        String pathUrl = JJTUrlConfigManager.getInstance().serverPathWithIdentity(getIdentity());
        return pathUrl;
    }

    @Override
    public Map<String, String> requestArgument() {
        JSONObject dataParameter = commonParameter();

        JSONObject parameterObject = JSON.parseObject(getParameters().toString());
        dataParameter.put("bizData", parameterObject);

        Map<String, String> map = JSONObject.parseObject(dataParameter.toJSONString(), new TypeReference<Map<String,String>>(){});
        return map;
    }

    @Override
    public void requestCompleteFilter() {
        super.requestCompleteFilter();

        String logMsg = "[response] host: " + this.hostUrl() + ", path: " + this.pathUrl();
        if (this.getResponseContentObject() != null) {
            logMsg += ", content: " + this.getResponseContentObject().toString();
        }
        JJLog.i(logMsg);

        processAbnormalStatus();
    }

    @Override
    public void requestFailedFilter() {
        super.requestFailedFilter();

        String logMsg = "[response] host: " + this.hostUrl() + ", path: " + this.pathUrl();
        if (this.getError() != null) {
            logMsg += ", error: " + this.getError().getMessage();
        }
        JJLog.w(logMsg);
    }

    @Override
    public boolean successForBussiness(Object model) {
        boolean successForBussiness = false;

        if (ReflectUtil.isInterface(model.getClass(), "com.mobileClientKernel.android.serviceLayer.httpTransportService.model.IJJTBaseModel")) {
            successForBussiness = ((IJJTBaseModel) model).isValid();
        }

        return successForBussiness;
    }

    @Override
    public Object convertToModel(String responseString) {
        Object object = null;
        try {
            object = JSON.parse(responseString);
        } catch (Exception e) {
            String logMsg = "JSON parse error, string: " + responseString + "; error: " + e.getMessage();
            JJLog.e(logMsg);
        }

        if (!(object instanceof com.alibaba.fastjson.JSONObject)) {
            String logMsg = "object is not com.alibaba.fastjson.JSONObject";
            JJLog.e(logMsg);
            return null;
        }
        JSONObject responseObject = (JSONObject) object;

        responseContentObject = responseObject;

        Object dataObject = getConvertModelContent(responseObject);

        IJJTBaseModel model;

        if (dataObject instanceof com.alibaba.fastjson.JSONObject) {
            String convertString = ((JSONObject) dataObject).toJSONString();
            model = (IJJTBaseModel) JSON.parseObject(convertString, getModelClass());
        } else if (dataObject instanceof com.alibaba.fastjson.JSONArray) {
            model = ReflectUtil.objectFromClass(getModelClass());
            List<Object> listModel = JSON.parseArray(((JSONArray) dataObject).toJSONString(), getModelClass());
            model.setResponseDataArray(listModel);
        } else if (dataObject instanceof String) {
            model = ReflectUtil.objectFromClass(getModelClass());
            model.setResponseDataString((String) dataObject);
        } else {
            model = ReflectUtil.objectFromClass(getModelClass());
        }

        try {
            org.json.JSONObject jsonObject = new org.json.JSONObject(responseObject.toString());
            model.setData(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return model;
    }

    @Override
    public void start() {
        super.start();

        String logMsg = "[request] host: " + this.hostUrl() + ", path: " + this.pathUrl() + ", parameters: " + this.parameters.toString();
        JJLog.i(logMsg);
    }

    public void processAbnormalStatus() {
        JJLog._d("JJTBaseRequest", "[processAbnormalStatus] responseContentObject = " + responseContentObject);
        //9308  9309
        if (responseContentObject!=null&&responseContentObject.containsKey("code")) {
            String code = (String) responseContentObject.get("code");
            JJLog._d("JJTBaseRequest", "[processAbnormalStatus] code = " + code);
            if ("9308".equals(code) || "9309".equals(code)) {
                Intent intent = new Intent();
                intent.setAction(FORCELOGOUT);
                intent.putExtra(FORCELOGOUT_CODE, code);
                intent.putExtra(FORCELOGOUT_CONTENT, responseContentObject.toString());
                //发送广播
                getContext().sendBroadcast(intent);
                JJLog._d("JJTBaseRequest", "[processAbnormalStatus] sendBroadcast!");
            }
        }
    }

    public Object getConvertModelContent(JSONObject object) {
        return object;
    }

    private JSONObject commonParameter() {
        JSONObject commonParams = new JSONObject();

        commonParams.put("channelType", "03");
        commonParams.put("clientVersion", "3.2.1");

        return commonParams;
    }

    public JSONObject getResponseContentObject() {
        return responseContentObject;
    }

    public org.json.JSONObject getParameters() {
        return parameters;
    }

    public boolean getIsEncryption() {
        return isEncryption;
    }

    public void setResponseContentObject(JSONObject responseContentObject) {
        this.responseContentObject = responseContentObject;
    }
}
